<?php


namespace App\Utils;


use App\Exceptions\SysException;

class Baidu
{
    static function geocoding($address)
    {
        $ak = config('app.baidu_ak_server');
        $url = "http://api.map.baidu.com/geocoding/v3/?address=$address&output=json&ak=$ak"; //GET请求
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $data = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        if (empty($data)) {
            throw new SysException('地址解析失败');
        }
        $result = json_decode($data, true);
        if ($result['status'] == 0) {
            return [$result['result']['location']['lat'], $result['result']['location']['lng']];
        }
        throw new SysException('地址解析失败:' . $data);
    }
}
